<!-- 甲方客户管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="园区名称">
                            <a-input v-model="parkName" placeholder="请输入园区名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="地区">
                            <a-cascader :options="options" :load-data="loadData" placeholder="请选择地区" change-on-select @change="onChange"/>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="state" placeholder="请选择" allow-clear @change="getData">
                                <a-select-option v-for="item in statusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                        <a-form-item label="创建时间">
                            <a-range-picker  format="YYYY-MM-DD" @change="onDateChange" allow-clear/>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                            <a-button style="margin-left: 20px" type='' @click="add">创建园区</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1200, }">
            <div slot="province" slot-scope="province,record">
                <a-tag :color="colors[0]">{{province}}-{{record.city}}-{{record.area}}</a-tag>
            </div>
            <div slot="registerType" slot-scope="registerType">
                <div v-for="(item,i) in registerTypeList" :key="item.id">
                    <a-tag v-if="item.id == registerType" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="createdBy" slot-scope="createdBy,record">
                <a-tag :color="colors[1]">{{record.updatedBy ? record.updatedBy : createdBy}}</a-tag>
            </div>
            <div slot="remark" slot-scope="remark">
                <ellipsis :length="18" tooltip>{{ remark == '' ? '-' : remark }}</ellipsis>
            </div>
            <div slot="state" slot-scope="state">
                <a-badge :status="state | statusTypeFilter" :text="state | statusFilter" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">详情</a-button>
                    <a-button type="link" @click="update(record)">编辑</a-button>
                    <a-button type="link" v-if="record.state == 0" @click="updateState(record,1)">启用</a-button>
                    <a-button type="link" class="errorColor" v-else @click="updateState(record,0)">停用</a-button>
                </div>
            </div>
        </a-table>

        <!-- 添加、修改园区信息 -->
        <a-modal 
            v-model="visible" 
            width="60%"
            :title="isAdd ? '添加园区信息' : '编辑园区信息'"
            @ok="handleOk" 
            :forceRender="true"
            @cancel="visible = false">
            <div>
                <a-form-model :model="item" ref="ruleForm" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="园区名称" prop="parkName">
                        <a-input v-model="item.parkName" placeholder="请输入园区名称" />
                    </a-form-model-item>
                    <a-form-model-item label="注册方式" prop="registerType">
                        <a-select v-model="item.registerType" placeholder="请选择注册方式">
                            <a-select-option v-for="item in registerTypeList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="地区" prop="area">
                        <a-cascader :options="options1" v-model="defaultValue" :load-data="loadData" placeholder="请选择地区" change-on-select @change="onSelChange"/>
                        <!-- <a-row :gutter='48'>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="item.province" placeholder="省份" @change="selProvince">
                                    <a-select-option v-for="item in provinceList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="item.city" placeholder="城市" @change="selCity">
                                    <a-select-option v-for="item in cityList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                            <a-col :md='8' :sm='24'>
                                <a-select v-model="item.area" placeholder="区域">
                                    <a-select-option v-for="item in areaList" :key="item.value" :value="item.label">{{item.label}}</a-select-option>
                                </a-select>
                            </a-col>
                        </a-row> -->
                        
                    </a-form-model-item>
                    <a-form-model-item label="备注">
                        <a-textarea v-model="item.remark" placeholder="请输入备注信息" :auto-size="{ minRows: 4, maxRows: 6 }" allow-clear/>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { industrialList , changeStateIndustrial , updateIndustrial } from '@/api/industrial';
import area from '@/assets/area';
import { Ellipsis } from '@/components';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            parkName: '', // 园区名称
            province: '', // 省份
            city: '', // 城市
            area: '', // 区域
            columns,
            total: 0,
            page: 1,
            size: 10,
            dataList: [],
            isload: false,
            state: undefined,
            statusList: [
                { id: 0, name: '已停用'},
                { id: 1, name: '使用中'},
            ],
            registerTypeList: [
                { id: 1, name: '线下注册'},{ id: 2, name: 'API注册'}
            ], // 注册方式，1：线下注册，2：API注册
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            options: [], // 地区 筛选
            provinceList: [],
            cityList: [],
            areaList: [],
            rules: {
                parkName: [
                    { required: true, message: '请输入园区名称', trigger: 'blur' },
                ],
                area: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
                registerType: [{ required: true, message: '请选择注册方式', trigger: 'blur'}],
            },
            item: {
                id: '',
                parkName: '', // 园区 名称
                registerType: undefined, // 注册方式
                province: '', // 省份
                city: '', // 城市
                area: '', // 区域
                remark: '', // 备注
            },
            defaultValue: [],
            isAdd: true,
            visible: false,
        };
    },
    created(){
        var list = [];
        for (const key in area.province_list) {
            if (area.province_list.hasOwnProperty(key)) {
                list.push({
                    'label': area.province_list[key],
                    'value': `${key}`,
                    'isLeaf': false,
                })
            }
        }
        this.provinceList = list;
        this.options = list;
        this.options1 = list;
        this.getData();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = date[0].format('YYYY-MM-DD')
                this.endTime = date[1].format('YYYY-MM-DD')
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this
            _this.isload = true;
            const params = {
                'parkName': _this.parkName, // 园区名称
                'province': _this.province, 
                'city': _this.city,
                'area': _this.area,
                'state': _this.state,
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'pageIndex': _this.page - 1,
                'pageSize': _this.size,
            }
            industrialList(params)
            .then(res=>{
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 状态切换
        updateState(item,state){
            let _this = this
            _this.$confirm({
                title: '温馨提示',
                content: state == 1 ? '是否确认开启当前园区' : '是否确认关闭当前园区',
                okText: state == 1 ? '确认开启' : '确认关闭',
                onOk() {
                    const params = {
                        'id': item.id,
                        'state': state,
                    }
                    changeStateIndustrial(params)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: state == 1 ? '开启成功' : '关闭成功',
                                duration: 8
                            })
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                },
                onCancel() {},
            });
        },
        // 添加园区
        add(){
            this.isAdd = true;
            this.item.id = '';
            this.item.parkName = '';
            this.item.registerType = undefined;
            this.province = '';
            this.city = '';
            this.area = '';
            this.remark = '';
            this.defaultValue = [];
            this.options1 = this.options;
            this.visible = true;
        },
        // 修改
        update(item){
            this.item = JSON.parse(JSON.stringify(item));
            this.isAdd = false
            this.defaultValue = [];
            var proCode = '';
            var cityCode = '';
            var areaCode = '';
            if(item.province != '' && item.city != '' && item.area != null){
                for (const key in area.province_list) {
                    if (area.province_list[key] == this.item.province) {
                        proCode = key;
                    }
                }
                var cityList = [];
                for (const key in area.city_list) {
                    if (area.city_list[key] == this.item.city && key.substring(0,2) == proCode.substring(0,2)) {
                        cityCode = key;
                    }
                    if(key.substring(0,2) == proCode.substring(0,2)){
                        cityList.push({
                            'label': area.city_list[key],
                            'value': key,
                            'isLeaf': false,
                        })
                    }
                }
                console.log(cityList,'citylist');
                this.options1[this.options1.findIndex(itm => itm.value == proCode)].children = cityList;
                var areaList = [];
                for (const key in area.county_list) {
                    if (area.county_list[key] == this.item.area && key.substring(0,4) == cityCode.substring(0,4)) {
                        areaCode = key;
                    }
                    if(key.substring(0,4) == cityCode.substring(0,4)){
                        areaList.push({
                            'label': area.county_list[key],
                            'value': key,
                        })
                    }
                }
                this.options1[this.options1.findIndex(itm => itm.value == proCode)].children[this.options1[this.options1.findIndex(itm => itm.value == proCode)].children.findIndex(im => im.value == cityCode)].children = areaList;
            }
            if(proCode != '' && cityCode != '' && areaCode != ''){
                this.defaultValue = [proCode,cityCode,areaCode];
            }
            console.log(this.defaultValue,'procode')
            this.visible = true;
        },
        // 确认添加、修改园区信息
        handleOk(){
            let _this = this;
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    updateIndustrial(_this.item).then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: _this.isAdd ? '添加成功' : '修改成功',
                                duration: 8
                            })
                            _this.visible = false;
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        onSelChange(value){
            if(value.length == 3){
                this.item.province = area.province_list[value[0]];
                this.item.city = area.city_list[value[1]];
                this.item.area = area.county_list[value[2]];
            }
            if(value.length == 0){
                this.item.province = '';
                this.item.city = '';
                this.item.area = '';
            }
        },
        onChange(value) {
            console.log(value,'values');
            if(value.length == 3){
                this.province = area.province_list[value[0]];
                this.city = area.city_list[value[1]];
                this.area = area.county_list[value[2]];
                this.getData();
            }
            if(value.length == 0){
                this.province = '';
                this.city = '';
                this.area = '';
                this.getData();
            }
        },
        loadData(selectedOptions) {
            console.log(selectedOptions,'selectedOptions')
            const targetOption = selectedOptions[selectedOptions.length - 1];
            targetOption.loading = true;
            let list = [];
            if(selectedOptions.length == 1){
                var provinceCode = targetOption.value.substring(0,2)
                for (const key in area.city_list) {
                    if (area.city_list.hasOwnProperty(key)) {
                        if(key.substring(0,2) == provinceCode){
                            list.push({
                                'label': area.city_list[key],
                                'value': key,
                                'isLeaf': false,
                            })
                        }
                    }
                }
            }else{
                var cityCode = targetOption.value.substring(0,4)
                for (const key in area.county_list) {
                    if (area.county_list.hasOwnProperty(key)) {
                        if(key.substring(0,4) == cityCode){
                            list.push({
                                'label': area.county_list[key],
                                'value': key,
                            })
                        }
                    }
                }
            }
            targetOption.loading = false;
            targetOption.children = list;
            this.options = [...this.options];
        },
        // 详情
        detail(item){
            this.$router.push({ path: '/industrial/industrialDetail', query: { 'detail': JSON.stringify(item)}})
        }
    }
}

</script>
<style scoped>

</style>